package coder

import (
	"encoding/binary"
	"github.com/sigurn/crc8"
)

func Crc(payload []byte) (crc byte) {
	var p = crc8.CRC8_DARC
	p.RefOut = false // 芯片的实现，和标准DARC本处不同: reverse_out为false
	table := crc8.MakeTable(p)
	crc = crc8.Checksum(payload, table)
	return
}

func BuildPacket(cmd byte, data []byte) (packet []byte) {
	// head cmd length
	packet = append(packet, PacketHead, cmd, byte(len(data)))
	// body
	packet = append(packet, data...)
	// crc tail
	packet = append(packet, Crc(packet), PacketTail)
	return
}

func BuildNestedPacket(cmd byte, body []byte) (packet []byte) {
	// head 00 00 cmd length body crc tail
	// head cmd length.
	// length部分为: body总长度,不包括其他内容
	packet = append(packet, PacketHead, 0x00, 0x00, cmd, byte(len(body)))
	// body
	packet = append(packet, body...)
	// crc tail
	packet = append(packet, Crc(packet), PacketTail)
	return
}

func BuildNestedSubPacket(cmd byte, body []byte) (packet []byte) {
	// cmd length 固定 body
	packet = append(packet, cmd, byte(len(body)), 0x5A, 0x6B, 0x7C, 0x8D)
	packet = append(packet, body...)
	return
}

func ReadUint16(p []byte) int {
	var v = binary.BigEndian.Uint16(p[:2])
	var value = int(v)
	return value
}
